package com.qinyi.framework.shiro.service;

import com.qinyi.common.ajax.AjaxCode;
import com.qinyi.common.exception.CustomException;
import com.qinyi.system.domin.SysUser;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangan on 2019/6/4
 * @description
 */
@Service
public class SysPasswordService {

    private Cache<String, AtomicInteger> loginRecordCache;

    @Autowired
    private CacheManager cacheManager;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @PostConstruct
    private void init() {
        loginRecordCache = cacheManager.getCache("loginRecordCache");
    }

    /**
     * 密码校验
     * 1.限制用户密码次数
     * 2.校验用户密码是否匹配
     *
     * @param user
     * @param password
     */
    public void volidate(SysUser user, String password) {
        String loginName = user.getLoginName();
        AtomicInteger retryCount = loginRecordCache.get(loginName);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(loginName, retryCount);
        }
        if (retryCount.incrementAndGet() > maxRetryCount) {
            throw new CustomException(AjaxCode.SERVER_ERROR, "密码错误次数超" + maxRetryCount + "次");
        }
        if (!match(password, user)) {
            loginRecordCache.put(loginName, retryCount);
            throw new CustomException(AjaxCode.SERVER_ERROR, "密码错误");
        }
        clearLoginRecordCache(loginName);

    }

    private boolean match(String password, SysUser user) {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), password, user.getSalt()));
    }

    private String encryptPassword(String loginName, String password, String salt) {
        String result = new Md5Hash(loginName + password + salt).toHex().toString();
        return result;
    }

    private void clearLoginRecordCache(String loginName) {
        loginRecordCache.remove(loginName);
    }

}
